import { action, observable } from 'mobx';
import { message } from 'antd';
import chatServer from '../services/chat';
import Base from './base';
import isSuccess from '../utils/error';
import { netCheckFn } from '../utils/netCheck';

const {
    getList, getDetail, getStages, getStagesDetail, selectTopic, nextStage, startStages, endStages
} = chatServer;

function sortCurrentStageTopics(currentStage) {
    let topics = currentStage.topics ? currentStage.topics.concat() : [];
    if (!!topics.length) {
        const cList = [];
        const uList = [];
        topics.forEach(t => {
            t.complete ? cList.push(t) : uList.push(t);
        });
        topics = [...uList, ...cList];
    };
    return { ...currentStage, topics }
}

export default class ChatState extends Base {

    constructor(props) {
        super(props);
        // 注入其它需要调用的store
        setTimeout(() => { })

    }

    @observable totalMsgCount = 0; // 未读消息总数
    totalMsgCount0 = 0; // 未完成未读消息总数(页面暂时不用到)
    @observable totalMsgCount1 = 0; // 已完成未读消息总数

    @observable chatList = []; // 左侧聊天列表数据
    @observable chatList0 = []; // 未完成项目聊天列表
    @observable chatList1 = []; // 已完成项目聊天列表

    @observable chatId = null; // 当前聊天组groupId
    @observable chatContent = {}; // 聊天内容，{ [chatId]: array }
    @observable chatListCurrentItem = undefined; // 后台列表接口返回的当前项目内容

    activeStageIndex = 0;
    @observable currentStage = {};
    @observable mustStages = [];
    @observable optionalStages = [];
    chatDraftCache = {}; // 暂存聊天输入框草稿 { [chatId]: string text }

    // 目前只有imsdk方法响应的时候才会调用这个getList方法
    @action.bound
    async getList(params = {}, recentMap, needUpdate) {
        let recentSessMap = recentMap;
        
        if (recentMap === null) {
            recentSessMap = this.recentSessMap;
        }
        this.recentSessMap = recentSessMap; // 缓存recentSessMap；
        
        let chatList = this.chatList;

        if (needUpdate) { // 如果是更新未读消息数就不再请求后台
            let res = await netCheckFn('chatList',async ()=>{
                const res = await getList(params);
                return res;
            })
            if (isSuccess(res)) {
                // console.log('---ChatState getList---', res, recentSessMap);
                chatList = res.data && Array.isArray(res.data) ? res.data : [];
            }
        }
        const hasRecent = [];
        const noRecent = [];

        let totalMsgCount0 = 0;
        let totalMsgCount1 = 0;
        chatList.forEach(v => {
            let has = false;
            const arr = v.groups.map(g => {
                const SessionItem = recentSessMap[`GROUP_${g.groupid}`];
                const activeId = window.localStorage.getItem('current-active-groupid');
                // if(g.groupid === activeId) {
                //     SessionItem.UnreadMsgCount += 1;
                // }
                if (SessionItem && SessionItem.MsgTimeStamp) {
                    has = true;

                    if (g.iscomplete) totalMsgCount1 += SessionItem.UnreadMsgCount;
                    else totalMsgCount0 += SessionItem.UnreadMsgCount;

                    return { ...g, SessionItem };
                }
                return { ...g, SessionItem: { MsgTimeStamp: 0, SessionId: g.groupid } }; // 没有聊天记录的小组也赋值一个默认值方便排序
            });

            // 组内排序由时间戳大到小排序
            const newGroups = arr.sort((a, b) => b.SessionItem.MsgTimeStamp - a.SessionItem.MsgTimeStamp);
            // 获取组内最大值，把最大值赋值到最外层
            const groupMax = newGroups[0].SessionItem.MsgTimeStamp;
            if (has) hasRecent.push({ ...v, groups: newGroups, groupMax });
            else noRecent.push({ ...v, groups: arr });
        });

        this.totalMsgCount = totalMsgCount0 + totalMsgCount1;
        this.totalMsgCount0 = totalMsgCount0;
        this.totalMsgCount1 = totalMsgCount1;

        // 最外层排序
        const sortedChatList = [...hasRecent.sort((a, b) => b.groupMax - a.groupMax), ...noRecent];
        console.log('----------------33333-----------------',sortedChatList);
        this.chatList = sortedChatList;
        if (sortedChatList.length) {
            const chatList0 = [];
            const chatList1 = [];
            sortedChatList.forEach(l => {
                l.groups[0].iscomplete ? chatList1.push(l) : chatList0.push(l);
            });
            this.chatList0 = chatList0;
            // 组内排序由完成时间大到小排序
            let sortChatList1 = chatList1;
            if (chatList1.length && chatList1.length > 1) {
                sortChatList1 = chatList1.concat().sort((a, b) => {
                    return Date.parse(new Date(b.completedtime)) - Date.parse(new Date(a.completedtime));
                });
            }
            this.chatList1 = sortChatList1;
        }
    }

    @action.bound
    async setChatDraftCache(chatId, stringText) {
        this.chatDraftCache = { ...this.chatDraftCache, [chatId]: stringText };
    }

    @action.bound
    async setChatContent(chatId, chatList) {
        this.chatId = chatId;
        this.chatContent = { [chatId]: chatList };
    }

    @action.bound
    async getDetail(chatListCurrentItem) {
        const { groupid, stageid, projecttype } = chatListCurrentItem.group;
        this.chatListCurrentItem = chatListCurrentItem;

        if (!(projecttype === 1 || projecttype === 2)) return

        // 获取聊天组的当前周期和周期详情
        // const detail = await getDetail({ groupid });
        
        let detail = await netCheckFn('chatDetail-' + groupid,async ()=>{
            const res = await getDetail({ groupid });
            return res;
        })
        if (!isSuccess(detail)) return;
        // console.log('---getDetail---', chatListCurrentItem, detail);
        const currentStage = detail.data;
        this.currentStage = sortCurrentStageTopics(currentStage);

        // 获取聊天组阶段
        // const data = await getStages({ groupid, stageid })
        let data = await netCheckFn('chatStages-' + groupid + '-' + stageid,async ()=>{
            const res = await getStages({ groupid, stageid })
            return res;
        })
        // console.log('---getStages---', data);

        const mustStages = [];
        const optionalStages = [];

        // 检查请求阶段列表的stageid是否有和currentStage的id是一致，没有则默认选中第一项
        let activeStageIndex = -1;

        if (data.data && data.data.length) {
            data.data.forEach((v, i) => {
                if (v.stagetype) optionalStages.push({ ...v, checked: v.branchstatus, hasLine: false });
                else {
                    const is = currentStage.stageid === v.stageid;
                    if (is) activeStageIndex = i;
                    mustStages.push({ ...v, checked: is, hasLine: is })
                };
            });

            if (activeStageIndex === -1) { // 没有当前stageid
                // 默认选中第一个周期 和 viewStage(mustStages[0].stageid)
                mustStages[0] = { ...mustStages[0], checked: true, hasLine: true };
                this.viewStage(mustStages[0].stageid);
                activeStageIndex = 0;
            }
        }
        this.activeStageIndex = activeStageIndex;
        this.mustStages = mustStages;
        this.optionalStages = optionalStages;
    }


    @action.bound
    async viewStage(stageid, isOption) {
        // 本地修改mustStages的状态
        const stages = this.mustStages.concat().map(v => ({ ...v, hasLine: !isOption ? (v.stageid === stageid) : false }));
        const options = this.optionalStages.concat().map(v => ({ ...v, hasLine: isOption ? (v.stageid === stageid) : false }));
        this.mustStages = stages;
        this.optionalStages = options;

        // const data = await getStagesDetail({
        //     groupid: this.currentStage.groupid,
        //     stageid,
        // })
        let data = await netCheckFn('chatStagesDetail-' + this.currentStage.groupid + '-' + stageid,async ()=>{
            const res = await getStagesDetail({
                groupid: this.currentStage.groupid,
                stageid,
            })
            return res;
        })
        if (isSuccess(data)) {
            // console.log('---getStagesDetail---', data);
            this.currentStage = sortCurrentStageTopics(data.data);
        }
    }

    @action.bound
    async selectTopic(t, index, callback) {
        const currentStage = this.currentStage;
        const topics = currentStage.topics.concat();
        topics[index] = { ...t, complete: !t.complete };
        currentStage.topics = topics;
        this.currentStage = currentStage;

        const params = topics.map(v => ({ topicid: v.topicid, ischecked: v.complete }));
        await selectTopic({
            groupid: currentStage.groupid,
            stageid: currentStage.stageid,
            topics: params
        });
        if(callback) callback(params);
    }

    @action.bound
    async nextStage({ nextstageIndex, ...params }, callback) {

        // const data = await nextStage(params);
        
        let data = await netCheckFn('chatNextStage',async ()=>{
            const res = await nextStage(params);
            return res;
        })
        // console.log('---nextStage---', data);

        if (!isSuccess(data) || !data.data.groupid) {
            callback(false);
            return;
        }

        // 本地修改状态
        this.activeStageIndex = nextstageIndex;
        this.currentStage = data.data;
        const mustStages = this.mustStages.concat().map((v, i) => {
            if (i === nextstageIndex) return { ...v, checked: true, hasLine: true };
            else return { ...v, checked: false, hasLine: false }
        });
        this.mustStages = mustStages;


        // 先相应回掉
        callback && callback(true)

        // 再修改列表状态
        this.getList({}, null, true);
        // if(this.chatListCurrentItem && this.chatListCurrentItem.group.grouptype === 1){
        //     const { stageid, stagename } = mustStages[nextstageIndex];
        //     try {
        //         this.chatList.forEach(v => {
        //             if(v.projectid === this.chatListCurrentItem.projectid) {
        //                 v.groups.forEach(g => {
        //                     if(g.groupid === this.chatListCurrentItem.group.groupid){
        //                         g.currentchatstagename = stagename;
        //                         g.currentchatstageid = stageid;

        //                     }
        //                 });
        //                 // 避免遍历太多，使用try catch捕捉错误的方式结束foreach循环
        //                 throw new Error('end foreach');
        //             }
        //         })
        //     } catch(e) {
        //         console.log('--终止foreach循环遍历');
        //     }
        // }
    }

    @action.bound
    async handleOptionStage(start, index) {
        const optionalStages = this.optionalStages.concat();
        const groupid = this.currentStage.groupid;
        const chatstageid = optionalStages[index].stageid;
        const fun = start ? startStages : endStages;
        const names = start ? 'startStages' : 'endStages';

        // const data = await fun({ groupid, chatstageid });
        let data = await netCheckFn(names + '-' + groupid + '-' + chatstageid,async ()=>{
            const res = await fun({ groupid, chatstageid });
            return res;
        })

        if (isSuccess(data) && data.success) {
            // 修改本地optionalStages的值
            optionalStages[index] = { ...optionalStages[index], checked: start, hasLine: false };
            this.optionalStages = optionalStages;

            if (start) return;
            const opsId = optionalStages[index].stageid;
            const currentId = this.currentStage.stageid;
            if (opsId === currentId) { // 当前展示的
                const viewId = this.mustStages[this.activeStageIndex].stageid;
                this.viewStage(viewId, false);
            }
        } else message.error('操作失败！')
    }

}